from django.db.models import F
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly

from .models import Post, Comment
from .serializers import (
    PostSerializer, PostDetailSerializer,
    CommentSerializer, CommentDetailSerializer
)
from .filters import PostFilter


class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.filter(status=Post.STATUS_NORMAL)
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    filter_class = PostFilter

    def retrieve(self, request, *args, **kwargs):
        self.serializer_class = PostDetailSerializer
        post = self.get_object()
        post.visitor_count = F('visitor_count') + 1
        post.save()
        return super().retrieve(request, *args, **kwargs)


class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects.filter(status=Comment.STATUS_NORMAL)
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

    def retrieve(self, request, *args, **kwargs):
        self.serializer_class = CommentDetailSerializer
        return super().retrieve(request, *args, **kwargs)
